package cn.yunbamboos.rest.service.converter;

import cn.yunbamboos.rest.service.dto.out.FileOutDTO;
import cn.yunbamboos.rest.service.logs.LogMetadataThreadLocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;

import java.io.IOException;

public class FileOutDTOToHttpMessageConverter extends DTOToHttpMessageConverter<FileOutDTO> {

    private static final Logger logger = LoggerFactory.getLogger(FileOutDTOToHttpMessageConverter.class);

    public FileOutDTOToHttpMessageConverter() {
        super(MediaType.APPLICATION_OCTET_STREAM);
    }

    @Override
    public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType){
        boolean result = FileOutDTO.class.isAssignableFrom(clazz);
        if (logger.isTraceEnabled()) {
            logger.trace("read {} {}", result, clazz);
        }
        return result;
    }

    @Override
    public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType){
        boolean result = FileOutDTO.class.isAssignableFrom(clazz);
        if (logger.isTraceEnabled()) {
            logger.trace("write {} {}", result, clazz);
        }
        return result;
    }

    @Override
    public FileOutDTO read(Class<? extends FileOutDTO> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(FileOutDTO out, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        HttpHeaders headers = outputMessage.getHeaders();
        headers.setContentType(contentType);
        LogMetadataThreadLocal.setCode(out.getCode());
        LogMetadataThreadLocal.setMsg(out.getMsg());
        outputMessage.getBody().write(out.toBytes());
    }
}
